package cn.jarlen.jwt.tools.menu;

import android.content.Context;
import android.widget.Toast;

import cn.jarlen.jwt.tools.utils.LittleUtils;

import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * @author jarlen
 * Create by 2023/4/12 13:50
 */
public class IPRead implements IMenuProcess {

    @Override
    public void onExecute(Context context) {
        String hostIp = getHostIP();

        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("终端IP查询结果:").append(LittleUtils.checkEmpty(hostIp));

        Toast.makeText(context, stringBuilder, Toast.LENGTH_LONG).show();
    }


    private static String getHostIP() {
        String hostIp = null;
        try {
            Enumeration nis = NetworkInterface.getNetworkInterfaces();
            InetAddress ia = null;
            while (nis.hasMoreElements()) {
                NetworkInterface ni = (NetworkInterface) nis.nextElement();
                Enumeration<InetAddress> ias = ni.getInetAddresses();
                while (ias.hasMoreElements()) {
                    ia = ias.nextElement();
                    if (ia instanceof Inet6Address) {
                        continue;// skip ipv6
                    }
                    String ip = ia.getHostAddress();
                    if (!"127.0.0.1".equals(ip)) {
                        hostIp = ia.getHostAddress();
                        break;
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return hostIp;

    }
}
